<template>
  <div v-show="showDialog && !detailInfo.visible">
    <div class="width100">
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slipSelectRequest="slipSelectRequest"
        >
        </new-page-filter>
        <el-button @click="closeDetailList">订单页</el-button>
      </div>
      <div class="filter-wrapper">
        <new-page-filter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-excel>
            <el-button @click="exportExcel()">导出excel </el-button>
          </template>
        </new-page-filter>
        <div class="display-flex">
          <Group-select
            :options="groupSelectInfo.options"
            v-model:selections="groupSelectInfo.selections"
            @callback="groupSelect"
            @callbackVal="updateGroupSelections"
          ></Group-select>
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        v-if="groupFlag"
        class="groupFlag-container"
        :is-group-search="true"
        v-model:data="groupSelectInfo.data"
        :field-list="tableInfo.fieldList"
        :check-box="false"
        :tab-index="false"
        :pager="false"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :span-method="arraySpanMethod"
        :row-class-name="tableRowClassName"
        @exChange="exChange"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          {{ scope.row.orderNo }}
        </template>
        <template v-slot:col-networkUnitScale="scope">
          {{
            scope.row.systemUnitCoefficient +
            scope.row.unitName +
            '=' +
            scope.row.networkUnitCoefficient +
            scope.row.networkUnit
          }}
        </template>
        <template v-slot:col-provinceAvailableQty="scope">
          <span
            v-if="
              scope.row.provinceAvailableQty ||
              scope.row.provinceAvailableQty === 0
            "
          >
            {{ scope.row.provinceAvailableQty + scope.row.networkUnit }}
          </span>
          <span v-else>-</span>
        </template>
        <template v-slot:col-sysQty="scope">
          <span v-if="scope.row.sysQty || scope.row.sysQty === 0">
            {{ scope.row.sysQty + scope.row.unitName }}
          </span>
          <span v-else>-</span>
        </template>
        <template v-slot:col-price="scope">
          <span v-if="scope.row.price || scope.row.price === 0">
            {{ scope.row.price + '元/' + scope.row.networkUnit }}
          </span>
          <span v-else>-</span>
        </template>
        <template v-slot:col-sysPrice="scope">
          <span v-if="scope.row.sysPrice || scope.row.sysPrice === 0">
            {{ scope.row.sysPrice + '元/' + scope.row.unitName }}
          </span>
          <span v-else>-</span>
        </template>
        <template v-slot:col-qty="scope">
          <span v-if="scope.row.qty || scope.row.qty === 0">
            {{ scope.row.qty + scope.row.networkUnit }}
          </span>
          <span v-else>-</span>
        </template>
        <template v-slot:col-provinceSumAmount="scope">
          <span
            v-if="
              scope.row.provinceSumAmount || scope.row.provinceSumAmount === 0
            "
          >
            {{ scope.row.provinceSumAmount + '元' }}
          </span>
          <span v-else>-</span>
        </template>
      </table-container>
      <table-container
        v-else
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :check-box="false"
        :tab-index="true"
        @pageInfo="pageInfo"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
        <template v-slot:col-networkUnitScale="scope">
          {{
            scope.row.systemUnitCoefficient +
            scope.row.unitName +
            '=' +
            scope.row.networkUnitCoefficient +
            scope.row.networkUnit
          }}
        </template>
        <template v-slot:col-provinceAvailableQty="scope">
          <span
            v-if="
              scope.row.provinceAvailableQty ||
              scope.row.provinceAvailableQty === 0
            "
          >
            {{ scope.row.provinceAvailableQty + scope.row.networkUnit }}
          </span>
          <span v-else>-</span>
        </template>
        <template v-slot:col-sysQty="scope">
          <span v-if="scope.row.sysQty || scope.row.sysQty === 0">
            {{ scope.row.sysQty + scope.row.unitName }}
          </span>
          <span v-else>-</span>
        </template>
        <template v-slot:col-price="scope">
          <span v-if="scope.row.price || scope.row.price === 0">
            {{ scope.row.price + '元/' + scope.row.networkUnit }}
          </span>
          <span v-else>-</span>
        </template>
        <template v-slot:col-sysPrice="scope">
          <span v-if="scope.row.sysPrice || scope.row.sysPrice === 0">
            {{ scope.row.sysPrice + '元/' + scope.row.unitName }}
          </span>
          <span v-else>-</span>
        </template>
        <template v-slot:col-qty="scope">
          <span v-if="scope.row.qty || scope.row.qty === 0">
            {{ scope.row.qty + scope.row.networkUnit }}
          </span>
          <span v-else>-</span>
        </template>
        <template v-slot:col-provinceSumAmount="scope">
          <span
            v-if="
              scope.row.provinceSumAmount || scope.row.provinceSumAmount === 0
            "
          >
            {{ scope.row.provinceSumAmount + '元' }}
          </span>
          <span v-else>-</span>
        </template>
      </table-container>
    </div>
  </div>
  <purch-order-detail
    v-if="detailInfo.visible"
    v-model:visible="detailInfo.visible"
    :orderId="detailInfo.orderId"
    @returnBack="getList"
  />
  <set-preference
    v-if="preferenceInfo.visible"
    v-model:visible="preferenceInfo.visible"
    :search-list="filterInfo.searchList"
    :field-list="tableInfo.fieldList"
    :customize-user-v-o="filterInfo.query.customizeUserVO"
    @callback="setPreferenceCallback"
  />
  <advanced-search
    v-if="advancedSearchInfo.visible"
    v-model:visible="advancedSearchInfo.visible"
    :field-list="tableInfo.fieldList"
    v-model:form-data="advancedSearchInfo.data"
    @callback="advancedSearchCallback"
  />
  <excelOrPrint :excelPrint="excelPrint"></excelOrPrint>
</template>
<script setup name="provincePurchDetailList">
import {
  getProvincePurchOrderDetailCustomizeListPage,
  excelProvincePurchOrderDetailCustomizeList,
  getProvincePurchOrderDetailCustomizeListAll,
  getProvincePurchOrderDetailCustomizeGroups,
} from '@/api/province'

import { getCustomizeSetting } from '@/api/customize'
import PurchOrderDetail from './detail'
const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps(['visible'])

// 过滤相关配置
const groupSelectInfo = ref({
  options: [],
  selections: [],
  data: [],
})
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    copyQueryMap: {},
    groupMap: {},
    groups: [],
    queryMap: {
      // deptAuth: {
      //   asTbName: 'purch_order',
      //   columnName: 'dept_id',
      //   queryType: 'IN',
      //   queryCategory: 'AND',
      //   value: 'deptAuth',
      // },
    },
    queryParams: {},
    customizeUserVO: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      value: 'excel',
      type: 'slot',
      show: proxy.$permission('provincePurch:excelDetailList'),
    },
  ],
})
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
})
//明细相关
const detailInfo = ref({
  visible: false,
  orderId: '',
})
const groupFlag = ref(false)

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})

setData()
function setData() {
  let obj = {
    qty: {
      label: '数量',
      value: 'qty',
      type: 'slot',
      minWidth: '250px',
      hidden: true,
    },
    price: {
      label: '单价',
      value: 'price',
      formatter: proxy.$fn.TripartiteMethod,
      type: 'slot',
      componentType: 'price',
      permission: !proxy.$permission('provincePurch:price'),
      hidden: true,
      show: false,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      formatter: proxy.$fn.TripartiteMethod,
      type: 'column',
      componentType: 'price',
      permission: !proxy.$permission('provincePurch:price'),
      hidden: true,
      show: false,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'column',
      componentType: 'price',
      permission: !proxy.$permission('provincePurch:price'),
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
      show: false,
    },
    statusValue: {
      label: '状态',
      value: 'statusValue',
      asValue: 'status',
      componentType: 'select-model',
      code: 'province_purch_detail_status',
      show: false,
      hidden: true,
    },
    sysPrice: {
      label: '系统单价',
      value: 'sysPrice',
      type: 'slot',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('provincePurch:price'),
      hidden: true,
    },
    provinceSumAmount: {
      label: '省采金额',
      value: 'provinceSumAmount',
      type: 'slot',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('provincePurch:price'),
      hidden: true,
    },
    provincePrice: {
      label: '省采单价',
      value: 'provincePrice',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('provincePurch:price'),
      hidden: true,
    },
    networkUnitScale: {
      label: 'SPD单位/省采单位',
      value: 'networkUnitScale',
      componentType: 'input',
      type: 'slot',
      hidden: true,
    },
    sysQty: {
      label: '系统采购数量',
      value: 'sysQty',
      type: 'slot',
      hidden: true,
    },
    provinceAvailableQty: {
      label: '省采可采购数量',
      value: 'provinceAvailableQty',
      type: 'slot',
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
    commonName: {
      label: '通用名称',
      value: 'commonName',
      componentType: 'input',
      show: false,
      hidden: true,
    },
  })
  getCustomize()
}
function closeDetailList() {
  proxy.$store.dispatch('app/toggleOpenFilter')
  showDialog.value = false
  emits('callback')
}
function updateGroupSelections(arr) {
  filterInfo.value.query.groups = arr
  groupSelectInfo.value.selections = arr
  if (!arr.length) {
    filterInfo.value.query.groups = []
    filterInfo.value.query.groupMap = {}
    groupSelectInfo.value.data = []
    groupFlag.value = false
  }
}
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const clearType = ref(true)
const slipSelectRequest = ref(true)
function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
// 获取列表
async function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
// function search() {
//   // 重置分页
//   advancedSearchInfo.value.data = {}
//   filterInfo.value.query.queryDtoList = []
//   tableInfo.value.initCurpage = Math.random()
//   tableInfo.value.refresh = Math.random()
// }
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
//导出excel
const excelPrint = ref({
  type: 'print', // 类型print/excel
  excel: {
    api: excelProvincePurchOrderDetailCustomizeList, // 导出数据接口
    params: {}, // 导出参数
  },
  refresh: null,
})
const page = ref({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
//打印导出分页参数
function pageInfo(obj) {
  page.value = obj
}
//导出
function exportExcel() {
  excelPrint.value.type = 'excel'
  excelPrint.value.excel.params = proxy.$fn.deepClone({
    ...proxy.$fn.delEmptyAttribute(filterInfo.value.query),
    ...page.value,
  })
  excelPrint.value.refresh = Math.random()
}
/* function exportExcel() {
  excelProvincePurchOrderDetailCustomizeList(filterInfo.value.query).then(
    (resp) => {
      if (resp) {
        proxy.$fn.parseExcel(resp)
      }
    }
  )
} */
//展示明细
function showDetail(row) {
  detailInfo.value.orderId = row.orderId
  detailInfo.value.visible = true
}
function groupSelect(arr) {
  if (arr.length) {
    //点击分组
    groupFlag.value = true
    filterInfo.value.query.groups = arr
    groupSelectInfo.value.selections = arr
    getCustomizeGroupsList()
  } else {
    proxy.$message.warning({
      message: '请选择分组条件！',
      showClose: true,
      duration: 3000,
    })
  }
}
async function getCustomizeGroupsList(len, param, expande) {
  //分组查询
  let params = {}
  if (len) {
    params = param
  } else {
    params = filterInfo.value.query
  }
  if (
    filterInfo.value.query.queryDtoList &&
    filterInfo.value.query.queryDtoList.length
  ) {
    params = proxy.$fn.deepClone(params)
    params.queryMap = {}
  }
  await getProvincePurchOrderDetailCustomizeGroups(params).then(async (res) => {
    if (res && res.success) {
      let data = res.data
      let newData = []
      if (len) {
        await data.forEach((item, index) => {
          newData.push({
            ...item,
            id: index + Math.random(),
            isColspan: true,
            children: [{ ...item, id: index + Math.random(), isColspan: true }],
          })
        })
        expande.children = newData
      } else {
        await data.forEach((item, index) => {
          newData.push({
            ...item,
            id: index + Math.random(),
            isColspan: true,
            children: [{ id: index + Math.random(), isColspan: true }],
          })
        })
        groupSelectInfo.value.data = newData
      }
    }
  })
}
function exChange(data, expandedRows) {
  //展开分组
  if (expandedRows) {
    let len = data.nextGroups.length
    if (len) {
      let params = {
        ...filterInfo.value.query,
        groups: data.nextGroups,
        groupMap: { ...data.query },
        queryMap: { ...filterInfo.value.query.queryMap, ...data.query },
      }
      getCustomizeGroupsList(len, params, data)
    } else {
      let params = {
        ...filterInfo.value.query,
        groups: [],
        groupMap: {},
        queryMap: { ...filterInfo.value.query.queryMap, ...data.query },
      }
      getProvincePurchOrderDetailCustomizeListAll(params).then(async (res) => {
        if (res && res.success) {
          let resData = res.data
          await resData.forEach((item, index) => {
            item.id = index + Math.random()
            item.isColspan = false
          })
          data.children = resData
        }
      })
    }
  } else {
    data.children = [{ id: Math.random(), isColspan: true }]
  }
}
async function advancedSearchCallback(obj) {
  let _filterInfo = filterInfo.value
  _filterInfo.query.queryMap = {}

  _filterInfo.query.queryDtoList = [...obj.queryDtoList]
  advancedSearchInfo.value.data = obj.data
  if (groupSelectInfo.value.selections.length > 0) {
    await getCustomizeGroupsList()
  } else {
    groupSelectInfo.value.data = []
    await getList()
  }
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  clearType.value = !clearType.value
}
// 搜索
function search() {
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  if (groupSelectInfo.value.selections.length > 0) {
    getCustomizeGroupsList()
  } else {
    groupSelectInfo.value.data = []
    tableInfo.value.initCurpage = Math.random()
    tableInfo.value.refresh = Math.random()
  }
}
function getCustomize(_slipSelectRequest = true) {
  let _tableInfo = tableInfo.value
  let _filterInfo = filterInfo.value
  let param = {
    tableKey:
      'provincePurchOrderDetailList-com.slip.spd.entity.vo.provincePlatform.ProvincePurchOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let searchInfo = proxy.$fn.setSearchList(
        _filterInfo.searchList,
        data.detail
      )
      let tableFieldInfo = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail,
        true
      )
      _tableInfo.fieldList = tableFieldInfo.fieldList
      groupSelectInfo.value.options = tableFieldInfo.groupOption
      _filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ..._filterInfo.query.queryMap,
      }
      _filterInfo.searchList = searchInfo.searchList
      _filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      _filterInfo.copyQueryMap = proxy.$fn.deepClone(_filterInfo.query.queryMap)
      slipSelectRequest.value = _slipSelectRequest
      _tableInfo.api = getProvincePurchOrderDetailCustomizeListPage
      getList()
    }
  })
}
function tableRowClassName(row) {
  if (row.row.nextGroups) {
    return 'bg-color-EBEEF5'
  } else {
    return ''
  }
}
function arraySpanMethod({ row, columnIndex }) {
  if (row.nextGroups) {
    if (columnIndex === 0) {
      return [1, tableInfo.value.fieldList.length + 1]
    }
  }
}
</script>

<style scoped></style>
